package com.orangelife.mobile.surrounding.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.common.sp.CommSp2;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.orangelife.mobile.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.IXListViewListener;
import com.orangelife.mobile.surrounding.adapter.GoodsClassifyListViewAdapter;
import com.orangelife.mobile.surrounding.entity.GoodsEntity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.fragment.OrangeLifeBaseFragment;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.ToastHelper;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 价格最低
 * 
 * @author Administrator
 * 
 */
public class GoodsClassifyLowestFragment extends OrangeLifeBaseFragment {
	private PullToRefreshListView lvList;
	private Handler mHandler;
	private List<Map<String, Object>> list;
	private List<Map<String, Object>> list2;
	/** 一页中数据的条数，初始设置为7条 */
	private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
	/** 初始页，初始化为第一页 */
	private int pageNo = Constant.PAGE_NO_DEFAULT;
	/** 优惠列表的adapter */
	private GoodsClassifyListViewAdapter<Map<String, Object>> adapter;
	private Dialog dialog;
	private View newView;
	/** 分辨是刷新还是加载更多 */
	private int flags = 1;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (newView == null) {
			newView = inflater.inflate(R.layout.fragment_hotest_listview, null);
			initView(newView);
			setAdapter();
			pullListView();
			getDataFromServer();
			// list.clear();
			pageNo = 1;
			getDiscountList(pageSize, pageNo);
		}
		/*
		 * 缓存的rootView需要判断是否已经被加过parent，
		 * 如果有parent需要从parent删除，要不然会发生这个view已经有parent的错误。
		 */
		ViewGroup parent = (ViewGroup) newView.getParent();
		if (parent != null) {
			parent.removeView(newView);
		}
		return newView;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onResume() {
		super.onResume();
		

	}

	/**
	 * 设置优惠列表的adapter
	 */
	private void setAdapter() {
		/* 设置listview的adapter */
		list = new ArrayList<Map<String, Object>>();
		list2 = new ArrayList<Map<String, Object>>();
		adapter = new GoodsClassifyListViewAdapter<Map<String, Object>>(
				getActivity(), list,false);
		lvList.setPullLoadEnable(false);
		lvList.setAdapter(adapter);
	}

	/**
	 * 初始化
	 * 
	 * @param view
	 */
	private void initView(View view) {
		lvList = (PullToRefreshListView) newView.findViewById(R.id.lv_discount);
		mHandler = new Handler();
	}

	/**
	 * 处理获得的数据
	 */
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 2:
				list2 = JsonReponseHandler.getListFromJson(
						String.valueOf(msg.obj), adapter, dialog);

				updateListView(list2);
				break;
			case 500:
				DialogHelper.closeDialog(dialog);
				ToastHelper.getInstance()._toast(
						msg.obj.toString());
				break;
			case 1011:
				isLogin(dialog);
				break;

			default:
				break;
			}
		}

	};

	/**
	 * 下拉刷新的进度条
	 */
	private void getDataFromServer() {
		dialog = DialogHelper.getInstance().createLoadingDialog(getActivity(),
				Constant.LOADING);
		dialog.show();
	}

	/**
	 * 获取列表数据
	 * 
	 * @param pageSize
	 *            每页的条数
	 * @param pageNo
	 *            初始页
	 */
	private void getDiscountList(int pageSize, int pageNo) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("comID", CommSp2.getCommID());
		map.put("goodsType",2);
		map.put("catID", GoodsEntity.getCatID());
//		map.put("catID", "");
		map.put("saleType",1);
		map.put("pageIndex", pageNo);
		map.put("pageSize", pageSize);
		map.put("order", 3);
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put("map", map);
		rootMap.put("url", Constant.URL_CIRCUMTESO_GOODSCLASSIFY_LIST);
		rootMap.put("wat", 2);
		new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
	}

	/**
	 * 下拉刷新列表
	 */
	private void pullListView() {
		lvList.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						// list.clear();
						flags = 1;
						pageNo = 1;
						getDiscountList(pageSize, pageNo);
						onLoad();
						adapter.setList(list);
						adapter.notifyDataSetChanged();
					}
				}, 2000);
			}

			@Override
			public void onLoadMore() {
				mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						flags = 0;
						pageNo += 1;
						getDiscountList(pageSize, pageNo);
						onLoad();
						if (list != null) {
							adapter.setList(list);
							adapter.notifyDataSetChanged();
						}
					}
				}, 2000);
			}
		});
	}

	/**
	 * 刷新 拉下列表
	 * 
	 * @param list2
	 */
	private void updateListView(List<Map<String, Object>> list2) {
		if (list2 == null) {
			lvList.setPullLoadEnable(false);
			if (flags == 1) {
				lvList.setPullLoadEnable(false);
				list.clear();
				adapter.setList(list);
				adapter.notifyDataSetChanged();
			}
		}
		if (list2 != null && list != null) {
			if (list2.size() == 0) {
				lvList.setPullLoadEnable(false);
				if(flags == 1){
					list.clear();
				}
				adapter.setList(list);
				adapter.notifyDataSetChanged();
			} else {
				if (flags == 1) {
					list.clear();
				}
				lvList.setPullLoadEnable(true);
				list.addAll(list2);
				adapter.setList(list);
				adapter.notifyDataSetChanged();

			}
		} else {
			lvList.setPullLoadEnable(false);
		}
	}

	@SuppressWarnings("deprecation")
	private void onLoad() {
		lvList.stopRefresh();
		lvList.stopLoadMore();
		lvList.setRefreshTime(new Date().toLocaleString());
	}
}
